import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import { isRelogin } from "@/utils/request";
// const token = localStorage.getItem('token')
import $http from "@/utils/http";
NProgress.configure({ showSpinner: false });

const whiteList = ["/login", "/register"];

router.beforeEach((to, from, next) => {
  if (localStorage.getItem("token")) {
    NProgress.start();
    to.meta.title && store.dispatch("settings/setTitle", to.meta.title);
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      console.log("store.getters.roles------用户角色列表", store.getters.roles.length);
      if (store.getters.roles.length === 0) {
        isRelogin.show = true;
        try {
          store
          .dispatch("GetInfo")
          .then(() => {
            isRelogin.show = false;
            store.dispatch("GenerateRoutes").then((accessRoutes) => {
              // 处理理由权限
              console.log("看看有没有token", localStorage.getItem("token"));
              if (!localStorage.getItem("token")) {
                store.dispatch('tagsView/delAllViews');
                next({ path: "/" });
                return;
              }
              let token = location.href.indexOf('token') != -1 ? location.href.split('token=')[1].split('#/')[0] : '';
              if (token) {
                localStorage.setItem("token",token)
              }
              router.addRoutes(accessRoutes); // 动态添加可访问路由表
              next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
            })
          })
        } catch (err) {
          store.dispatch("LogOut").then(() => {
            Message.error(err);
            next({ path: "/" });
          });
        }
      } else {
        next();
      }
    }
  } else {
    let token =
      location.href.indexOf("token") != -1
        ? location.href.split("token=")[1].split("#/")[0]
        : "";
    console.log(location.href, "sssssssss", token);
    // // 单点登录
    if (token) {
      localStorage.setItem("token", token);
      next();
    }
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
